#!/usr/bin/perl

# 1.0 Initialize

require "getopts.pl";

&Getopts("vhrf:");

if ($#ARGV < 0 &&!defined($opt_h) &&!defined($opt_v)) {
    print STDERR "Try: 'holog_rdbe -h'\n";
    exit -1;
}

if(defined($opt_v)) {
    print "[holog_rdbe 1.0]\n";
    exit -1;
}

if (defined($opt_h)) {
    print "Usage: holog_rdbe input rdbe output\n";
    print "Synopsis: extracts rdbe dbe_tsys data from a FS log\n";

    print "This script processes log files to an space delimited file if the dbe_tsys data for an RDBE.\n";
    print "It will abort if any of the selected rdbe's dbe_tsys has noin-zero return code or if the IF\n";
    print "channel changes in the log file. This script is useful for extracting data from the FS program";
    print "HOLOG if is using dbe_tsys? commands for sampling.\n";

    print "\nArguments:\n";
    print "  input  - FS log file to process, must exist:\n";
    print "  rdbe   - RDBE to extract data for 'a', 'b', 'c', or 'd':\n";
    print "  output - Output file, must not exist:\n";

    print "\nOption:\n";
    print " -v print program and PGPLOT version information\n";
    print " -h print this help information and stop\n";
    exit -1;
}

# 2.0 extract data

my ($file,$rdbe,$out)= @ARGV;

#print "args '$file' '$rdbe' '$out'\n";

if(not defined $out) {
    die "Three arguments are required, giving up.\n";
}
if(!($rdbe =~ /^[abcd]$/)) {
    die "Second argument must be 'a', 'b', 'c' or 'd', not '$rdbe', giving up.\n";
}

open(FILE,$file) || do {
    print STDERR "Can't open input $file: '$file', giving up.\n";
    exit -1;
};

if (-e $out) {
    die "Output file '$out' already exists, giving up.\n";
}

open(OUT,'>',$out) || do {
    print STDERR "Can't open output '$file', giving up.$!\n";
    exit -1;
};


$first = 1;
while (<FILE>) {
    if(!/rdbe$rdbe\/\!dbe_tsys/i) {
	next;
    }
    chomp;
    $line = $_;
    $line =~ s/^.*tsys\?//;
    @fields=split(/[:;]/,$line);
    $return_code=shift(@fields);
    if($return_code  ne "0") {
	die "Giving up, non-zero return code '$return_code' found in '$_'\n";
    }

    $this_if=shift(@fields);
    if($first) {
	$first=0;
	$if0=$this_if;
    }
    if($if0 ne $this_if) {
	die "Giving up, different IF '$this_if' found in '$_'\n";
    }

    print OUT join(" ",@fields),"\n";
}
